const express = require("express");
const router = express.Router();
const { Article } = require("../../models");
const { success, failure } = require("../../utils/responses");
const { paging } = require("../../utils/utils");
const { NotFoundError } = require("../../utils/errors");

/**
 * 查询文章列表
 * GTE  /articles
 */
router.get("/", async function (req, res, next) {
  // 查询所有数据
  try {
    // 获取分页参数
    const { query, currentPage, pageSize, offset } = paging(req);
    // 排序+分页
    const condition = {
      attributes: { exclude: ["content"] },
      order: [["id", "DESC"]],
      limit: pageSize,
      offset: offset,
    };
    // 分页查询
    const { count, rows } = await Article.findAndCountAll(condition);
    // 返回
    success(res, "文章查询成功", {
      articles: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});
/**
 * 查询文章详情
 * GTE  /articles/:id
 */
router.get("/:id", async function (req, res, next) {
  try {
    const { id } = req.params;
    const article = await Article.findByPk(id);
    if (!article) {
      throw new NotFoundError(`ID: ${id} not found`);
    }
    // 返回
    success(res, "查询文章成功", { article });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
